/**
 * 
 */
package com.alphasystem.commerce.common.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;

/**
 * @author Syed F Ali
 * 
 */
public class AppUtil {
	private static ClassLoader classLoader = null;

	// protected static Logger logger = Logger.getLogger(AppUtil.class);

	public static final String NEW_LINE = System.getProperty("line.separator");

	static {
		classLoader = Thread.currentThread().getContextClassLoader();
	}

	/**
	 * @param d
	 * @param numOfDays
	 * @return
	 */
	public static Date addToDate(Date d, int numOfDays) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(d);
		cal.add(Calendar.DAY_OF_MONTH, numOfDays);
		return cal.getTime();
	}

	/**
	 * @param path
	 * @return
	 * @throws FileNotFoundException
	 */
	public static File findFile(String path) throws FileNotFoundException {
		URL url = getUrl(path);

		String fileName = null;
		if (url != null) {
			fileName = url.getFile();
		} else {
			fileName = path;
		}

		try {
			fileName = URLDecoder.decode(fileName, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		File file = null;
		if (fileName != null) {
			file = new File(fileName);
		}

		if (!file.exists()) {
			throw new FileNotFoundException("File \"" + file.getAbsolutePath()
					+ "\" does not exists.");
		}

		return file;

	}

	/**
	 * @param path
	 * @return
	 * @throws FileNotFoundException
	 */
	public static String getAbsolutePath(String path)
			throws FileNotFoundException {
		return findFile(path).getAbsolutePath();
	}

	public static String getClassName(String className) {
		return className.substring(className.lastIndexOf('.') + 1);
	}

	protected static String getFormattedPath(String path) {
		path = path.replace('.', '/');
		int lastIndex = path.lastIndexOf('/');
		if (lastIndex > -1) {
			path = path.substring(0, lastIndex) + "."
					+ path.substring(lastIndex + 1, path.length());
			// logger.trace("Path name is: " + path);
		}
		return path;
	}

	public static InputStream getResourceAsStream(String path) {
		return classLoader.getResourceAsStream(getFormattedPath(path));
	}

	public static Enumeration<URL> getResources(String path) {
		try {
			return classLoader.getResources(path);
		} catch (IOException e) {
			// logger.error(e.getMessage(), e);
		}
		return null;
	}

	public static String getStackTrace(Throwable exception) {
		StringBuffer stackTrace = new StringBuffer();
		if (exception == null) {
			String result = stackTrace.toString();
			// reset the string buffer
			stackTrace.setLength(0);
			return result;
		}
		stackTrace.append(exception.getClass().getName() + ":"
				+ exception.getMessage() + NEW_LINE);
		StackTraceElement[] ste = exception.getStackTrace();
		for (int i = 0; i < ste.length; i++) {
			stackTrace
					.append("\tat " + getStackTraceElement(ste[i]) + NEW_LINE);
		}
		stackTrace.append(getStackTrace(exception.getCause())).append(NEW_LINE);
		return stackTrace.toString();
	}

	/**
	 * DOCUMENT ME!
	 * 
	 * @param ste
	 *            DOCUMENT ME!
	 * @return DOCUMENT ME!
	 */
	private static String getStackTraceElement(StackTraceElement ste) {
		StringBuffer result = new StringBuffer();
		result.append(ste.getClassName() + "." + ste.getMethodName() + "(");
		if (ste.isNativeMethod()) {
			result.append("Native Method");
		} else {
			String fileName = ste.getFileName();
			int lineNumber = ste.getLineNumber();
			if (fileName == null) {
				result.append("Unknown Source");
			} else {
				result.append(fileName);
			}
			if (lineNumber > 0) {
				result.append(":" + lineNumber);
			}
		}
		result.append(")");
		return result.toString();
	}

	public static URL getUrl(String path) {
		String resName = path.replace('.', '/');
		int lastIndex = resName.lastIndexOf("/");
		resName = resName.substring(0, lastIndex) + "."
				+ resName.substring(lastIndex + 1, resName.length());

		URL url = null;
		if (classLoader != null) {
			url = classLoader.getResource(resName);
		} else {
			url = ClassLoader.getSystemResource(resName);
		}
		return url;
	}

	@SuppressWarnings("rawtypes")
	public static Class resolveClass(String className) {
		try {
			return Class.forName(className);
		} catch (ClassNotFoundException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}
}
